package com.king.tv.http;

import android.content.Context;
import com.king.tv.App;
import com.king.tv.util.MD5;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * API客户端接口：用于访问网络数据
 * 
 * @author t E-mail:wangh@appsino.com
 * @version 创建时间：2013-3-21 下午12:10:36
 * @Copyright (c) 2013 风语者科技（北京）.Co.Ltd. All rights reserved.
 * 
 */

public class ApiClient {

	private static ApiClient mInstance;
	private static Context mContext;
	private App myapplication;
//	private static String V = "";
	// private static final String V = "11";
	private static final String SRC = "2";
	private static final String APP_ID = "6666";
	private static final String SECRET_KEY = "wqerf*5508";

	private ApiClient(Context context) {
		ApiClient.mContext = context;
		this.myapplication = (App) context.getApplicationContext();
//		V = AppUtils.getAppUtils(appContext).getPackageInfo().versionName;

	}

	private static class ApiClientHolder {
		private static Context context;

		public ApiClientHolder(Context context) {
			ApiClientHolder.context = context;
		}

		public static ApiClient INSTANCE = new ApiClient(context);
	}

	public static ApiClient getInstance(Context context) {
		synchronized (ApiClient.class) {
			if (mInstance == null) {
				mInstance = new ApiClient(context);
			}
			return mInstance;
		}
	}

	/**
	 * 制造包含sig 的请求参数
	 * 
	 * @return
	 */
	public static HashMap<String, Object> createParams(HashMap<String, Object> params) {
		params = makeParamMap(params);
		return params;
	}

	/******************** api系统级别方法S *********************/
	public static HashMap<String, Object> makeParamMap(HashMap<String, Object> paramMap) {
		if (paramMap == null) {
			paramMap = new HashMap<String, Object>();
		}
		String params = "";
		paramMap.put("app_id", APP_ID);
		paramMap.put("appType","1");
		paramMap.put("v", "2.6.2");
		paramMap.put("src", SRC);
		params = generateNormalizedString(paramMap);
		String forMakeSigStr = params + SECRET_KEY;
		String sig = MD5.getMD5(forMakeSigStr).toLowerCase();
		paramMap.put("v", "2.6.2");
		paramMap.put("sig", sig);
		paramMap.put("src", SRC);
		paramMap.put("appType","1");
		paramMap.put("app_id", APP_ID);
		return paramMap;
	}

	private final static String generateNormalizedString(HashMap<String, Object> paramMap) {
		Set<String> params = paramMap.keySet();
		List<String> sortedParams = new ArrayList<String>(params);
		Collections.sort(sortedParams);
		StringBuilder sb = new StringBuilder();
		for (String paramKey : sortedParams) {
			// 参数值只取前5000个字符
			sb.append(paramKey).append('=').append(org.apache.commons.lang3.StringUtils.substring(String.valueOf(paramMap.get(paramKey)), 0, 5000));
		}
		return sb.toString();
	}
}
